package cn.edu.niit.dao;

import cn.edu.niit.db.JDBCUtil;
import cn.edu.niit.javabean.Message;

import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class MessageDao {
    public List<Message> getAllMessages() {
        String sql = "select * from message order by public_date desc";
        ResultSet rs = JDBCUtil.getInstance().executeQueryRS(sql, new Object[]{});
        List<Message> messages = new ArrayList<>();
        try {
            while (rs.next()) {
                Message message = Message.builder().id(rs.getString("id")).cardId(rs.getString("card_id"))
                        .detail(rs.getString("detail"))
                        .publicDate(rs.getTimestamp("public_date")).build();
                messages.add(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }

    public int addMessage(String detail, String id) {
        String sql = "insert into message(card_id,detail,public_date) values(?,?,?)";
        return JDBCUtil.getInstance().executeUpdate(sql, new Object[]{id, detail, new Timestamp(System.currentTimeMillis())});
    }
}
